from rest_framework import serializers

from social.account.models import User
from social.call.models import AVCall
from social.exceptions import CodeException, InsufficientBalanceException
from social.payment.models import Wallet
from social.user.models import AVCallSetting, UserBlock, UserCallData
from social.user.serializers import SimpleUserSerializer
from social.utils.serializers import HashidField


class AVCallSerializer(serializers.ModelSerializer):
    id = HashidField(model=AVCall)
    from_user = serializers.SerializerMethodField(required=False)
    to_user = serializers.SerializerMethodField(required=False)

    def get_from_user(self, instance):
        return SimpleUserSerializer(instance.from_user).data

    def get_to_user(self, instance):
        return SimpleUserSerializer(instance.to_user).data

    def create(self, validated_data):
        request = self.context['request']
        from_user = request.user
        user_id = str(request.data.get('user_id'))
        to_user = User.objects.get(id=user_id)
        if UserBlock.is_block(from_user, to_user):
            raise CodeException(msg='您已拉黑了对方，无法发起通话')
        if UserBlock.is_blocked(from_user, to_user):
            raise CodeException(msg='对方已拉黑了您，无法发起通话')

        _type = validated_data.get('type')

        if to_user.gender == 'g' and to_user.avatar_auth:
            # 被呼叫方是主播
            if from_user.gender == 'g':
                raise CodeException('无法发起通话')
            who_pay = 'from'
            av_call_setting, _ = AVCallSetting.objects.get_or_create(user=to_user)
            video_price, audio_price = av_call_setting.call_price
            coin = video_price if _type == 'video' else audio_price
            wallet, _ = Wallet.objects.get_or_create(user=from_user)
            if wallet.balance < coin:
                raise InsufficientBalanceException()
        elif from_user.gender == 'g' and to_user.avatar_auth:
            if to_user.gender == 'g':
                raise CodeException('无法发起通话')
            who_pay = 'to'
            av_call_setting, _ = AVCallSetting.objects.get_or_create(user=to_user)
            video_price, audio_price = av_call_setting.call_price
            coin = video_price if _type == 'video' else audio_price
            wallet, _ = Wallet.objects.get_or_create(user=to_user)
            if wallet.balance < coin:
                raise CodeException(msg='对方余额不足，无法发起通话')
        else:
            raise CodeException(msg='无法发起通话')
        av_call = AVCall.objects.create(from_user=from_user, to_user=to_user, who_pay=who_pay, coin=coin, type=_type)
        return av_call

    class Meta:
        model = AVCall
        fields = ('id', 'coin', 'from_user', 'to_user', 'status', 'type', 'coin', 'who_pay', 'call_id')
